package com.didispace.web.fallback;

import com.alibaba.fastjson.JSONObject;
import com.didispace.web.ComputeApi;
import com.netflix.hystrix.exception.HystrixBadRequestException;
import feign.hystrix.FallbackFactory;
import org.springframework.stereotype.Component;

/**
 * @author liangqq
 */
@Component
public class ComputeApiFallback implements FallbackFactory<ComputeApi> {
    @Override
    public ComputeApi create(Throwable throwable) {
        //这里的异常是被Feign封装过的异常，不能直接在异常信息中看出原始方法抛出的异常。

        //实际的报错信息如下：
        //status 500 reading ComputeApi#throwsBizException(); content:
        // {"timestamp":"2019-06-19T11:45:51.439+0000","status":500,"error":"Internal Server Error","message":"业务异常！","path":"/throwsBizException"}

        //尝试获取第二行，
        String errorMsg = throwable.getMessage();
        String[] strings = errorMsg.split("\\n");
        if(strings.length > 1){
            String jsonStr = strings[1];
            try{
                JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                String providerErrorMsg = jsonObject.getString("message");
                throw new HystrixBadRequestException(providerErrorMsg);
            }catch (Exception e){
                //解析异常，将原来的错误信息抛出
                throw new RuntimeException(throwable.getMessage());
            }
        }
        throw new RuntimeException(throwable.getMessage());
    }
}
